<script setup lang="ts">
import { getConsultOrderPre, createConsultOrder } from '@/api/consult'
import { getPatientDetail } from '@/api/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { onMounted, ref } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { onBeforeRouteLeave } from 'vue-router'
import { useRouter } from 'vue-router'
const store = useConsultStore()
const router = useRouter()
// 1. 查询预订单信息
const payInfo = ref<ConsultOrderPreData>()
const loadData = async () => {
  try {
    const { data: res } = await getConsultOrderPre({
      type: store.consult.type,
      illnessType: store.consult.illnessType
    })
    console.log('=预订单信息', res)
    payInfo.value = res
    // 设置默认优惠券
    store.setCoupon(res.couponId)
  } catch (error) {
    console.log(error)
    showToast('缺失参数重新选择')
    router.push('/')
  }
}

// 2. 查询患者信息
const patient = ref<Patient>()
const loadPatient = async () => {
  if (!store.consult.patientId) return
  const { data: res } = await getPatientDetail(store.consult.patientId)
  console.log('=患者信息', res)

  patient.value = res
}

onMounted(() => {
  loadData()
  loadPatient()
})

// // 3.支付弹窗
const agree = ref(false)
const show = ref(false)
// // 支付方式
// // 买家账号：jfjbwb4477@sandbox.com
// // 登录密码：111111
// // 支付密码：111111
const orderId = ref('')
const submit = async () => {
  try {
    if (!agree.value) return showToast('请勾选我已同意支付协议')
    //当我们尝试访问或设置不包含在对象类型中的属性时，会出现“Property does not exist on type ‘{}’ ”错误
    const { data: res } = await createConsultOrder(store.consult)
    console.log('=创建订单', res)
    orderId.value = res.id
    store.clear()
  } catch (err) {
    console.log('=监控报错', err)
  }
  //   // 打开
  show.value = true
}
// //  4.支付窗口打开后，订单创建成功
onBeforeRouteLeave(() => {
  // 存在订单ID，说明订单已经创建成功了，页面不能再执行跳转
  if (orderId.value) return false
})

const onClose = async () => {
  try {
    await showConfirmDialog({
      title: '关闭支付',
      message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelButtonText: '仍要关闭',
      confirmButtonText: '继续支付',
      confirmButtonColor: 'var(--cp-primary)'
    })
    return false
  } catch {
    orderId.value = '' // 清空后才能跳转页面
    router.push('/user/consult')
    return true
  }
}

// // 跳转支付
// const pay = async () => {
//   // 注意支付方式0微信，不能做!判断
//   if (paymentMethod.value === undefined) return showToast('请选择支付方式')
//   showLoadingToast('跳转支付')
//   try {
//     const { data } = await getConsultOrderPayUrl({
//       orderId: orderId.value,
//       paymentMethod: paymentMethod.value,
//       payCallback: 'http://localhost:5173/room'
//     })
//     // http://localhost:5173/room?orderId=6885025887227904&payResult=true&type=2
//     console.log('=支付地址', data)
//     window.location.href = data.payUrl
//   } catch (err) {
//     console.log(err)
//   }
// }
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <!-- 1. 支付信息 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo?.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo?.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo?.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 2. 患者信息  -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient?.name} | ${patient?.genderValue} | ${patient?.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 3. 打开支付弹层并创建问诊订单,此处用非空断言 -->
    <van-submit-bar
      button-type="primary"
      :price="payInfo?.actualPayment! * 100"
      button-text="立即支付"
      text-align="left"
      @click="submit"
    />

    <!-- 支付弹层 -->
    <cp-pay-sheet
      v-model:show="show"
      :orderId="orderId"
      :actualPayment="payInfo?.actualPayment"
      :onClose="onClose"
    />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;
    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }
    .desc {
      flex: 1;
      > span {
        display: block;
        color: var(--cp-tag);
        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }
  .pay-price {
    ::v-deep() {
      .vam-cell__title {
        font-size: 16px;
      }
      .van-cell__value {
        font-size: 16px;
        color: var(--cp-price);
      }
    }
  }
  .pay-space {
    height: 12px;
    background-color: var(--cp-bg);
  }
  .pay-schema {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    .text {
      color: var(--cp-primary);
    }
  }
  ::v-deep() {
    .van-submit-bar__button {
      font-weight: normal;
      width: 160px;
    }
  }
}
// // 支付弹层样式
// .pay-type {
//   .amount {
//     padding: 20px;
//     text-align: center;
//     font-size: 16px;
//     font-weight: bold;
//   }
//   .btn {
//     padding: 15px;
//   }
//   .van-cell {
//     align-items: center;
//     .cp-icon {
//       margin-right: 10px;
//       font-size: 18px;
//     }
//     .van-checkbox :deep(.van-checkbox__icon) {
//       font-size: 16px;
//     }
//   }
// }
</style>
